import { _decorator, Component, Node, Label, Prefab, Event, find, sys, director, UITransform, tween, v3, game, v2, Widget, UIOpacity, log, instantiate, EventTouch, RigidBody2D, ERigidBody2DType, RichText, ScrollView, assetManager, Texture2D, Sprite, macro, SpriteFrame, PhysicsSystem2D, Collider2D, Vec3, Vec2 } from 'cc';
const { ccclass, property } = _decorator;

import BallSc from "./BallSc";
import SaveUtils from "./My/SaveUtils";
import Global from "./My/AD/platform/Global";
import { GameData, SaveData } from "./My/GlobalDefine";
import { Common } from "./My/Common";
enum GameState {
    start, gaming, over
}

@ccclass('GameSc')
export default class GameSc extends Component {
    now_All_fruit: Node[] = [];
    timer_jindu: number = 0;
    @property(Label)
    scoreLabel: Label | null = null;
    @property(Label)
    ComboLabel: Label | null = null;
    @property(Label)
    RewardLabel: Label | null = null;
    combocounter = 0
    nowCombo = 0
    nowReward = 0
    comboTimer = 0
    nowRewardEND = 0
    @property(Node)
    ballsLayer: Node | null = null;
    @property(Prefab)
    waterEffectPrefab: Prefab | null = null;
    @property(Prefab)
    wanneng: Prefab | null = null;
    @property(Prefab)
    boom: Prefab | null = null;
    @property(Prefab)
    boomtx: Prefab | null = null;
    @property([Prefab])
    ballsPrefab: Prefab[] = [];
    @property(Prefab)
    ppppp: Prefab | null = null;
    @property(Node)
    deadLine: Node | null = null;
    @property(Node)
    WarnLine: Node | null = null;
    @property(Label)
    fenSum: Label | null = null;;
    @property(Label)
    topScore: Label | null = null;
    @property(Node)
    history: Node | null = null;
    @property(Node)
    btn_back: Node | null = null;;
    @property(Node)
    btn_again: Node | null = null;;
    @property(Node)
    box_rule: Node | null = null;
    @property(Prefab)
    tips: Prefab | null = null;
    @property(Node)
    AdImg: Node | null = null;
    private fetching: boolean = false;
    private randomArray = [0, 0, 0, 0, 1, 1, 2, 3];
    private alreadyrandomArray = [];//已经解锁的水果
    private currentBall: Node | null = null;
    private nextBall: Node | null = null;
    private currentBallIndex: number = 0;
    public _gameState: GameState = GameState.gaming;
    static _instance = null;
    public _isReplay = false;
    public _xiguaSum: number = 0;
    public _isStart = true;
    public _lvl8 = false;
    private _score: number = 0;
    public get score(): number {
        return this._score;
    }
    static get Instance(): GameSc {
        return GameSc._instance;
    }
    public getGameState() {
        return GameState;
    }
    public set score(v: number) {
        this._score = v;
        this.scoreLabel.string = v.toFixed(0);
        tween(this.scoreLabel.node)
            .to(0.15,
                { scale: v3(1.5, 1.5, 1.5) },
            )
            .to(0.1,
                { scale: v3(1, 1, 1) },
            )
            .start();
    }
    timer: number = 0//计时器
    isXiaochu: boolean = false;//是否启用了消除道具
    ishuan: boolean = false;//是否启用了换一换道具
    @property(Node)
    NOpower: Node | null = null;
    @property(Node)
    meig: Node | null = null;
    CreateNum: number = 0//水果生成次数
    iscloseHighlight: boolean = false//当局是否关闭过高亮提示
    @property(Node)
    Panel_Prop_tap: Node | null = null;//敲一敲弹窗面板
    @property(Node)
    Panel_Prop_swap: Node | null = null;//换一换弹窗面板
    @property(Node)
    Panel_Prop_shake: Node | null = null;//摇一摇弹窗面板
    @property(Node)
    Panel_Prop_wan: Node | null = null;//万能弹窗面板
    Num_qyq: number[] = [0, 1]//当前敲一敲次数
    Num_hyh: number[] = [0, 1]//当前换一换次数
    Num_yyy: number[] = [0, 1]//当前摇一摇次数
    Num_wan: number[] = [0, 1]//当前万能次数
    Num_boom: number[] = [0, 1]//当前炸弹次数
    @property(Node)
    Panel_Rank: Node | null = null;//排行榜弹窗面板
    @property(Node)
    ComboRankPanal: Node | null = null;//combo排行榜弹窗面板
    @property(Node)
    ComboRankcontent: Node | null = null;//combo排行榜弹窗面板内容
    @property(Node)
    Panel_Star: Node | null = null;//开始弹窗面板
    iszjtsl: boolean = false;//这局提示使用道具了吗
    @property(Node)
    NowRankBG: Node | null = null;//本期排名面板
    @property(Node)
    LastRankBG: Node | null = null;//上期排名面板
    isStar: boolean = false//游戏是否开始
    AllRankInfo: any[] = []//所有的排名信息
    AllRankInfoLast: any[] = []//所有的排名信息
    @property(Prefab)
    ItemPrefab: Prefab | null = null;
    isWUDI: boolean = false//是否是无敌状态
    youRank: number = -1
    isUpdateRank: boolean = false;
    play_id: number = 0
    @property(Label)
    downTimeLabel: Label | null = null;
    downTime: number = 100000//赛事倒计时
    nextBallIndex: number = 1//下一个球的序号
    onLoad() {

        SaveUtils.inst.getLocalData()
        // director.getPhysicsManager().enabled = true;
        PhysicsSystem2D.instance.enable = true;

        let drift = Math.random() > 0.5 ? 1 : -1;
        // director.getPhysicsManager().gravity = v2(drift, -1280);
        PhysicsSystem2D.instance.gravity = v2(drift, -1280);

        this.deadLine.getComponent(Widget).updateAlignment();

        find("Canvas/Panel_Rank/BG/NowRankBG/item/Score").getComponent(Label).string = SaveData.MaxScore[0] + ""
        if (SaveData.MaxScore[0] == undefined) SaveData.MaxScore = [0, 0]
        find("Canvas/Main/0/Score").getComponent(Label).string = "最高分：" + SaveData.MaxScore[0]
        find("Canvas/Main/1/Score").getComponent(Label).string = "最高分：" + SaveData.MaxScore[1]
        find("Canvas/Main/2/Score").getComponent(Label).string = "第 " + SaveData.PaoPaoLevel + " 关"
    }
    start() {
        // 广告 连击停留时间 连击额外分数 死亡倒计时 合成额外加分 合成额外加分概率 幸运度
        // Global.platform.CREATE_BANNER();
        // Global.platform.ONLOAD_BANNER();
        // Global.platform.CREATE_TITIALAD();
        // Global.platform.GmmeQuan();

        // Global.platform.GetUserInfo()//申请权限 =>成功获取昵称头像


        GameSc._instance = this;
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);

        this.CreateNewBall();
        //死亡线在球接近的时候闪烁
        this.deadLine.active = false;

        tween(this.deadLine.getComponent(UIOpacity)).repeatForever(
            tween(this.deadLine.getComponent(UIOpacity))
                .to(0.3, { opacity: 0 })
                .to(0.3, { opacity: 255 })
        ).start();
        tween(this.WarnLine.getComponent(UIOpacity)).repeatForever(
            tween(this.WarnLine.getComponent(UIOpacity))
                .to(0.3, { opacity: 0 })
                .to(0.3, { opacity: 255 })
        ).start();

        director.preloadScene("Game", function () {
            log("Next scene preloaded");
        });
        // tween(find("Canvas/box_rule/label")).repeatForever(
        //     tween(find("Canvas/box_rule/label"))
        //         .to(1, { opacity: 155, scale: v3(0.9, 0.9, 0.9) })
        //         .to(1, { opacity: 255, scale: v3(1, 1, 1) })
        // ).start();

        let labelNode = find("Canvas/box_rule/label")!;

        // 确保节点有 UIOpacity 组件
        let uiOpacity = labelNode.getComponent(UIOpacity);
        if (!uiOpacity) {
            uiOpacity = labelNode.addComponent(UIOpacity);
        }
        // tween 同时操作 scale 和 uiOpacity.opacity
        tween({ scale: labelNode.scale.clone(), opacity: uiOpacity.opacity })
            .repeatForever(
                tween()
                    .to(1, { scale: v3(0.9, 0.9, 0.9), opacity: 155 })
                    .to(1, { scale: v3(1, 1, 1), opacity: 255 })
                    .call((target: any) => {
                        // 把 tween 值应用到节点和组件
                        labelNode.setScale(target.scale);
                        uiOpacity.opacity = target.opacity;
                    })
            )
            .start();

        // let labelNode = find("Canvas/box_rule/label")!;
        // // 确保有 UIOpacity 组件
        // let uiOpacity = labelNode.getComponent(UIOpacity);
        // if (!uiOpacity) {
        //     uiOpacity = labelNode.addComponent(UIOpacity);
        // }
        // tween(labelNode)
        //     .repeatForever(
        //         tween()
        //             .to(1, {
        //                 scale: v3(0.9, 0.9, 0.9)
        //             })
        //             .call(() => { uiOpacity!.opacity = 155; })
        //             .to(1, {
        //                 scale: v3(1, 1, 1)
        //             })
        //             .call(() => { uiOpacity!.opacity = 255; })
        //     )
        //     .start();



        // this.ProgressDetection()
        //保存数据
        SaveUtils.inst.SaveData()

    }
    //    //检查游戏进度
    ProgressDetection() {
        if (SaveData.GameData[GameData.gameModel].length != 0) {
            for (let index = 0; index < SaveData.GameData[GameData.gameModel].length; index++) {
                let ball = instantiate(this.ballsPrefab[SaveData.GameData[GameData.gameModel][index].index - 1])
                this.ballsLayer.addChild(ball);
                ball.setPosition(SaveData.GameData[GameData.gameModel][index].x, SaveData.GameData[GameData.gameModel][index].y)
                this.now_All_fruit.push(ball)
            }
            this.score = SaveData.GameDataScore[GameData.gameModel]
            this.Num_qyq[0] = SaveData.GameDataProp[GameData.gameModel][0]
            this.Num_wan[0] = SaveData.GameDataProp[GameData.gameModel][1]
            this.Num_yyy[0] = SaveData.GameDataProp[GameData.gameModel][2]
            if (SaveData.GameDataProp[GameData.gameModel][0] != 0) find("Canvas/Prop/Layout/tap").active = false
            if (SaveData.GameDataProp[GameData.gameModel][1] != 0) find("Canvas/Prop/Layout/wan").active = false
            if (SaveData.GameDataProp[GameData.gameModel][2] != 0) find("Canvas/Prop/Layout/shake").active = false
        }
    }
    //    /** 松开弹射 */
    private onTouchEnd(e: EventTouch) {
        if (this._isReplay) {
            return;
        }
        if (this._gameState !== GameState.gaming) {
            return;
        }
        if (!this.currentBall) {
            return;
        }
        if (this.isXiaochu == true) {
            // let temp = director.getPhysicsManager().testPoint(e.touch.getLocation());
            // let selectNode = director.getPhysicsManager().testPoint(e.touch.getLocation());

            let touchPos = e.getLocation();
            // 在 3.8 里直接用 PhysicsSystem2D.instance.testPoint
            let selectNode = PhysicsSystem2D.instance.testPoint(touchPos)[0];

            if (selectNode) {
                const eff = instantiate(this.waterEffectPrefab);
                // eff.x = selectNode.node.x;
                // eff.y = selectNode.node.y;
                eff.position = v3(selectNode.node.position.x, selectNode.node.position.y);
                // eff.color = GameData.ballColors[selectNode.getComponent(BallSc).BallIndex - 1];
                eff.getComponent(Sprite).color = GameData.ballColors[selectNode.getComponent(BallSc).BallIndex - 1];
                this.ballsLayer.addChild(eff);
                Common.spliceOneFromAll(this.now_All_fruit, selectNode)
                selectNode.node.active = false
                this.isXiaochu = false;
                // 胜利的判断
            } else {
                //提示消息
                this.meigg("选择一个你想要消除的水果", false);
            }
            return;
        }
        let ball = this.currentBall;
        ball.addComponent(BallSc).BallIndex = this.currentBallIndex;
        this.currentBall = null;
        // let x = this.ballsLayer.getComponent(UITransform).convertToNodeSpaceAR(e.getLocation()).x;


        let uiTransform = this.ballsLayer.getComponent(UITransform);
        let touchPos = e.getLocation();
        let worldPos = new Vec3(touchPos.x, touchPos.y, 0);
        let localPos = uiTransform.convertToNodeSpaceAR(worldPos);
        let x = localPos.x;



        find("Canvas/bg/indicate").active = false

        if (x > 720 / 2 - ball.getComponent(UITransform).width / 2) {
            x = 720 / 2 - ball.getComponent(UITransform).width / 2;
        } else if (x < -720 / 2 + ball.getComponent(UITransform).width / 2) {
            x = -720 / 2 + ball.getComponent(UITransform).width / 2;
        }
        // find('Canvas/bg/indicate').x = x;
        find('Canvas/bg/indicate').position = v3(x, find('Canvas/bg/indicate').position.y, find('Canvas/bg/indicate').position.z);
        let speed = 1 / 1000;

        // 计算目标位置
        let targetPos = ball.position.clone();
        targetPos.x = x;
        tween(ball)
            // .to(Math.abs(speed * x), { x })
            .to(Math.abs(speed * x), { position: targetPos })
            .call(() => {
                ball.getComponent(RigidBody2D).type = ERigidBody2DType.Dynamic;
                ball.getComponent(RigidBody2D).linearVelocity = v2(0, -300);
                this.now_All_fruit.push(ball);
                this.CreateNewBall();
            })
            .start();
    }
    private onTouchMove(e: EventTouch) {
        if (this.isXiaochu == true) { return }
        if (this._gameState == GameState.gaming) {
            if (this.currentBall) {
                find("Canvas/bg/indicate").active = true
                // let x = this.ballsLayer.getComponent(UITransform).convertToNodeSpaceAR(e.getLocation()).x;

                let touchPos = e.getLocation();
                // 转成 Vec3 再转换坐标
                let localPos = this.ballsLayer
                    .getComponent(UITransform)
                    .convertToNodeSpaceAR(new Vec3(touchPos.x, touchPos.y, 0));
                let x = localPos.x;


                if (x > 720 / 2 - this.currentBall.getComponent(UITransform).width / 2) {
                    x = 720 / 2 - this.currentBall.getComponent(UITransform).width / 2;
                } else if (x < -720 / 2 + this.currentBall.getComponent(UITransform).width / 2) {
                    x = -720 / 2 + this.currentBall.getComponent(UITransform).width / 2;
                }
                // this.currentBall.x = x;
                // find('Canvas/bg/indicate').x = x;
                this.currentBall.position = v3(x, this.currentBall.position.y, this.currentBall.position.z)
                find('Canvas/bg/indicate').position = v3(x, find('Canvas/bg/indicate').position.y, find('Canvas/bg/indicate').position.z)

            }
        }
    }
    onRandmoIndex(isProp: boolean = false) {
        var randomIndex
        if (isProp) {
            randomIndex = this.alreadyrandomArray[Math.floor(Math.random() * this.alreadyrandomArray.length)];
        } else {
            randomIndex = this.randomArray[Math.floor(Math.random() * this.randomArray.length)];
            // if (!this.alreadyrandomArray.includes(randomIndex)) { this.alreadyrandomArray.push(randomIndex); }
        }
        return this.onSelectLvl(randomIndex);
    }
    onSelectLvl(lvl) {
        if (lvl >= 9) {
            lvl = 7;
            return lvl;
        }
        else
            if (lvl == 8) {
                if (!this._lvl8) {
                    this._lvl8 = true;
                    return lvl;
                } else {
                    this.onRandmoIndex();
                }
            } else {
                return lvl;
            }
    }
    //    /** 创建一个新的球在等待射击的位置上 */
    private CreateNewBall(status = false, isProp: boolean = false, index: number = 999) {
        this.CreateNum += 1
        // 如果之前的球存在则销毁它
        if (this.currentBall) {
            this.currentBall.destroy();
        }
        let randomIndex = this.nextBallIndex
        this.nextBallIndex = this.onRandmoIndex(isProp);
        let ball
        if (index == 0) {
            ball = instantiate(this.wanneng);
        } else if (index == -1) {
            ball = instantiate(this.boom);
        } else {
            ball = instantiate(this.ballsPrefab[randomIndex]);
        }
        this.currentBallIndex = ball.getComponent(BallSc).BallIndex;
        ball.removeComponent(BallSc);
        if (this._isStart) {
            find('Canvas/topNode').getComponent(Widget).updateAlignment();
            this._isStart = false;
        }
        ball.y = find('Canvas/topNode').position.y;
        //ball.x=find("Canvas/bg/indicate").x;
        // find("Canvas/bg/indicate").x = 0
        find("Canvas/bg/indicate").position = v3(0, find("Canvas/bg/indicate").position.y, find("Canvas/bg/indicate").position.z)

        ball.getComponent(RigidBody2D).type = ERigidBody2DType.Static;
        ball.scale = 0;

        this.scheduleOnce(() => (
            this.CreateNextBall(this.nextBallIndex)
        ))

        tween(ball)
            .delay(0.2)
            .call(() => {
                this.ballsLayer.addChild(ball);
            })
            .to(0.25, { scale: 1.1 })
            .to(0.15, { scale: 0.9 })
            .to(0.07, { scale: 1 })
            .call(() => {
                this.currentBall = ball;
                if (status) {
                    this._isReplay = false;
                    this._gameState = GameState.gaming;
                }
            }).start();
    }
    CreateNextBall(randomIndex: number) {
        if (this.nextBall) {
            this.nextBall.destroy();
        }
        let ball = instantiate(this.ballsPrefab[randomIndex]);
        ball.removeComponent(BallSc);
        ball.removeComponent(Collider2D);
        ball.getComponent(RigidBody2D).type = ERigidBody2DType.Static;
        ball.parent = find('Canvas/nexttopNode')
        // ball.y = 0
        ball.position = v3(0, ball.position.y, ball.position.z);

        this.nextBall = ball;
        // ball.setContentSize(60, 60)
        ball.getComponent(UITransform)!.setContentSize(60, 60);

        ball.scale = v3(0, 0, 0);
        tween(ball)
            .delay(0.2)
            .to(0.25, { scale: v3(1.1, 1.1, 1.1) })
            .to(0.15, { scale: v3(0.9, 0.9, 0.9) })
            .to(0.07, { scale: v3(1, 1, 1) })
            .start();
    }
    public BallLevelUp(target: Node, other: Node) {
        let index = target.getComponent(BallSc).BallIndex + 1;
        if (index <= this.ballsPrefab.length) {
            game.emit('game-ball-levelup');

            other.getComponent(Collider2D).enabled = false;
            // tween(other).to(0.15, { x: target.x, y: target.y })
            tween(other).to(0.15, { position: v3(target.position.x, target.position.y) })
                .removeSelf()
                .call(() => {
                    if (index == 11) {
                        this._xiguaSum++;
                        this.openWin()
                    }
                    const newBall = instantiate(this.ballsPrefab[index - 1]);
                    newBall.position = target.position;
                    // newBall.x = target.x;
                    // newBall.y = target.y;
                    newBall.position = v3(target.position.x, target.position.y, target.position.z);
                    // if (GameData.gameModel == 1) newBall.getComponent(RigidBody2D).linearVelocity = v2(0, 10).mul(100);
                    if (GameData.gameModel == 1) {
                        let rb = newBall.getComponent(RigidBody2D);
                        if (rb) {
                            rb.linearVelocity = new Vec2(0, 10).multiplyScalar(100);
                        }
                    }


                    newBall.scale = v3(0, 0, 0);
                    tween(newBall)
                        .to(0.2,
                            { scale: v3(1.2, 1.2, 1.2) },
                            //{ easing: easeBackOut().easing }
                        )
                        .to(0.1,
                            { scale: v3(0.8, 0.8, 0.8) },
                        )
                        .to(0.1,
                            { scale: v3(1, 1, 1) },
                        )
                        .start();
                    this.ballsLayer.addChild(newBall);
                    this.now_All_fruit.push(newBall);
                    // target.removeFromParent(true);
                    target.removeFromParent();

                    Common.spliceOneFromAll(this.now_All_fruit, target)
                    Common.spliceOneFromAll(this.now_All_fruit, other)
                    const eff = instantiate(this.waterEffectPrefab);
                    // eff.x = newBall.x;
                    // eff.y = newBall.y;
                    eff.position = v3(newBall.position.x, newBall.position.y, newBall.position.z);
                    eff.getComponent(Sprite).color = GameData.ballColors[index - 1];
                    this.ballsLayer.addChild(eff);
                })
                .start();
            this.score += target.getComponent(BallSc).BallIndex;
            // 对随机范围作扩充
            if (this.randomArray.findIndex((value) => {
                return value == index - 2;
            }) < 0 && index < 10) {
                this.randomArray = this.randomArray.concat(this.randomArray).sort((a, b) => { return a - b; });
                this.randomArray.push(index - 2);
            }

            return true;
        } else {
            return false;
        }
    }
    combo(num: number) {
        this.combocounter++
        this.nowReward += num
        if (this.combocounter >= 2) {
            this.nowCombo++
            if (this.nowCombo > 1) {
                this.ComboLabel.string = this.nowCombo + " 连击"
                this.nowRewardEND = Math.ceil(this.nowReward * this.nowCombo * this.nowCombo * 0.01)
                this.RewardLabel.string = "连击奖励+" + this.nowRewardEND
                tween(this.ComboLabel.node)
                    .to(0.15,
                        { scale: v3(1.5, 1.5, 1.5) },
                    )
                    .to(0.1,
                        { scale: v3(1, 1, 1) },
                    )
                    .start();
            }
            this.combocounter = 0;
            this.comboTimer = 0;
        }
    }
    update(dt) {
        if (this._gameState == GameState.gaming) {
            //进度保存
            {
                this.timer_jindu++
                if (this.timer_jindu >= 100) {
                    this.timer_jindu = 0
                    SaveData.GameData[GameData.gameModel] = []

                    for (let index = 0; index < this.now_All_fruit.length; index++) {
                        let now = this.now_All_fruit[index]
                        if (now.getComponent(BallSc)) SaveData.GameData[GameData.gameModel].push({ "x": now.position.x, "y": now.position.y, "index": now.getComponent(BallSc).BallIndex })
                    }
                    SaveData.GameDataProp[GameData.gameModel] = [this.Num_qyq[0], this.Num_wan[0], this.Num_yyy[0]]
                    SaveData.GameDataScore[GameData.gameModel] = this.score
                    SaveUtils.inst.SaveData()
                }
            }
            //连击处理
            {
                this.comboTimer++
                if (this.comboTimer >= 120) {
                    if (this.ComboLabel.string != "") {
                        {
                            if (SaveData.ComboList[GameData.gameModel].length < 10) {
                                SaveData.ComboList[GameData.gameModel].push({ score: this.nowRewardEND, combo: this.nowCombo, date: Common.getNowTime() })
                            }
                            else if (this.nowRewardEND > SaveData.ComboList[GameData.gameModel][SaveData.ComboList[GameData.gameModel].length - 1].score) {
                                SaveData.ComboList[GameData.gameModel].pop()
                                SaveData.ComboList[GameData.gameModel].push({ score: this.nowRewardEND, combo: this.nowCombo, date: Common.getNowTime() })
                            }
                            let sortedArray: { score: number; combo: number; date: string; }[] = SaveData.ComboList[GameData.gameModel].sort((a, b) => {
                                if (a.score > b.score) {
                                    return -1
                                }
                                if (a.score < b.score) {
                                    return 1
                                }
                                return 0
                            })
                            SaveData.ComboList[GameData.gameModel] = sortedArray
                            SaveUtils.inst.SaveData()
                        }
                        this.score += this.nowRewardEND
                        tween(this.scoreLabel.node)
                            .to(0.15,
                                { scale: v3(1.7, 1.7, 1.7) },
                            )
                            .to(0.1,
                                { scale: v3(1, 1, 1) },
                            )
                            .start();
                        this.nowReward = 0;
                        this.ComboLabel.string = ""
                        this.RewardLabel.string = ""
                    }

                    this.nowCombo = 0;
                }
            }
            const arr = this.ballsLayer.getComponentsInChildren(BallSc);
            let warning: boolean = false;
            let over: boolean = false;
            for (let ball of arr) {
                if (!ball.isNotCheckOver) continue;
                if (ball.node.position.y >= this.deadLine.position.y * 0.6) {
                    this.WarnLine.active = true;
                    if (ball.node.position.y >= this.deadLine.position.y - ball.node.getComponent(UITransform).height / 2) {
                        warning = true;
                    }
                    if (!this.iszjtsl && SaveData.isPropts) { this.shou(); this.iszjtsl = true }
                    //break
                }
            }
            if (warning && !this.isWUDI) { this.timer += 1; if (this.timer >= 400) { over = true; } } else { this.timer = 0 }

            if (this.WarnLine.active) {
                let pp = 0
                for (let ball of arr) {
                    if (ball.node.position.y >= this.deadLine.position.y * 0.6) {
                        pp++
                        break
                    }
                }
                if (pp == 0) this.WarnLine.active = false
            }
            this.deadLine.active = warning;

            if (over) {
                //游戏结束，进度清空
                SaveData.GameData = []
                SaveData.GameDataScore[GameData.gameModel] = 0
                SaveData.GameDataProp = []


                for (let ball of arr) {
                    if (!ball.isNotCheckOver) continue;
                    ball.getComponent(RigidBody2D).type = ERigidBody2DType.Static;
                }
                this._isReplay = true;
                this._gameState = GameState.over;


                find('Canvas/OverUI').active = true;
                this.Panel_Prop_tap.active = false; this.Panel_Prop_swap.active = false; this.Panel_Prop_shake.active = false; this.Panel_Rank.active = false
                let s = this.score.toString()
                find("Canvas/OverUI/frame_blue/fenSum").getComponent(Label).string = s
                find("Canvas/OverUI/frame_blue/fenSum/fenSum").setPosition(46 + (s.length - 1) * 16, -6.5)

                let ranknow
                if (this.youRank <= 0) {
                    ranknow = "100+"
                } else {
                    ranknow = this.youRank
                }
                if (Global.avatarUrl != "") {
                    if (SaveData.MaxScore[GameData.gameModel] < this.score) {
                        SaveData.MaxScore[GameData.gameModel] = this.score
                        if (GameData.gameModel == 0) this.UpdateGameData(this.score)
                    } else {
                        if (GameData.gameModel == 0) this.UpdateGameData(SaveData.MaxScore[GameData.gameModel])
                    }
                }
                find("Canvas/OverUI/frame_blue/di1/RichText").getComponent(RichText).string =
                    "<color=#C88442>本期最高分数</c><color=#F14B3E>" + SaveData.MaxScore[GameData.gameModel] + "</color><color=#C88442>分</c>"
                find("Canvas/OverUI/frame_blue/di2/RichText").getComponent(RichText).string =
                    "<color=#C88442>你的排名</c><color=#F14B3E>" + ranknow + "</color><color=#C88442>名</c>"
                SaveUtils.inst.SaveData()
                return
            }
        }
    }
    onClickOpenUrl() {
        find('Canvas/OverUI').active = true;
    }
    replay() {
        if (SaveData.power >= 0) {
            // Global.platform.HIDE_BANNER()
            director.loadScene("Game");

        } else {
            this.NOpower.active = true
            find("/BG/Label2", this.NOpower).active = false
            find("/BG/Label1", this.NOpower).active = true
        };
    }
    ruleTapEffect() {
        this.box_rule.active = false;
    }
    closeWin() {
        find('Canvas/WinUI').active = false;
    }
    openWin() {
        let panal = find('Canvas/WinUI')
        panal.active = true;

        panal.scale = v3(0, 0, 0)
        panal.getChildByName("start").active = false
        tween(panal)
            .to(0.5,
                { scale: v3(1.3, 1.3, 1.3) },
            )
            .to(0.2,
                { scale: v3(1, 1, 1) },
            ).call(() => { panal.getChildByName("start").active = true })
            .start();
    }
    //    //打开关闭:道具
    OpenClose_Prop(event: Event, customEventData: string) {
        this.closeHighlight()
        switch (customEventData) {
            case "万能关闭": this.Panel_Prop_wan.active = false; director.resume(); break;
            case "万能":
                if (this.Num_wan[0] < this.Num_wan[1]) {
                    this.Panel_Prop_wan.active = true;
                    director.pause();
                } else {
                    this.meigg("万能水果用光了！", false)
                }
                break;
            case "10": this.Panel_Prop_tap.active = false; director.resume(); break;
            case "11":
                if (this.Num_qyq[0] < this.Num_qyq[1]) {
                    this.Panel_Prop_tap.active = true;
                    director.pause();
                } else {
                    this.meigg("敲一敲次数用光了！", false)
                }
                break;
            case "20": this.Panel_Prop_swap.active = false; director.resume(); break;
            case "21":
                if (this.Num_hyh[0] < this.Num_hyh[1]) {
                    this.Panel_Prop_swap.active = true;
                    director.pause()
                } else {
                    this.meigg("换一换次数用光了！", false)
                }
                break;
            case "30": this.Panel_Prop_shake.active = false; director.resume(); break;
            case "31":
                if (this.Num_yyy[0] < this.Num_yyy[1]) {
                    this.Panel_Prop_shake.active = true;
                    director.pause()
                } else {
                    this.meigg("摇一摇次数用光了！", false)
                }
                break;
            case "40": this.Panel_Rank.active = false;
                director.resume();
                break;
            case "41":
                this.Panel_Rank.active = true;
                break;
            case "50":
                if (SaveData.power >= 2) {
                    this.Panel_Star.active = false;
                    director.resume();
                    this.isStar = true
                } else {
                    this.NOpower.active = true
                    find("/BG/Label2", this.NOpower).active = false
                    find("/BG/Label1", this.NOpower).active = true
                };
                break;
            case "51": if (!this.isStar) this.Panel_Star.active = true; break;
            case "60": this.LastRankBG.active = true; this.NowRankBG.active = false; break;
            case "61": this.LastRankBG.active = false; this.NowRankBG.active = true; break;
            case "70": this.meigg("暂无", false); break;
            case "80": find("Canvas/Prop").active = false; break;
            case "81": find("Canvas/Prop").active = true; break;
            case "90":
                if (SaveData.power >= 2) {
                    this.Panel_Rank.active = false;
                    director.resume();
                    find("/more", this.LastRankBG).active = true
                    find("/share", this.LastRankBG).active = true
                    find("/close", this.LastRankBG).active = true
                    find("/close", this.NowRankBG).active = true
                    find("/star", this.LastRankBG).active = false
                    this.isStar = true

                } else {
                    this.NOpower.active = true
                    find("/BG/Label2", this.NOpower).active = false
                    find("/BG/Label1", this.NOpower).active = true
                };
            case "100": break;
            case "110": find("Canvas/Panel_Rank/BG/NowRankBG/Gui").active = true; find("Canvas/Panel_Rank/BG/NowRankBG").getComponent(ScrollView).enabled = false; break;
            case "111": find("Canvas/Panel_Rank/BG/NowRankBG/Gui").active = false; find("Canvas/Panel_Rank/BG/NowRankBG").getComponent(ScrollView).enabled = true; break;
            case "120": this.scheduleOnce(() => {
                this.ComboRankPanal.active = true;
            });
                {
                    for (let index = 0; index < SaveData.ComboList[GameData.gameModel].length; index++) {
                        this.ComboRankcontent.children[index].children[0].getComponent(Label).string = SaveData.ComboList[GameData.gameModel][index].score + "";
                        this.ComboRankcontent.children[index].children[1].getComponent(Label).string = SaveData.ComboList[GameData.gameModel][index].combo + "";
                        this.ComboRankcontent.children[index].children[2].getComponent(Label).string = SaveData.ComboList[GameData.gameModel][index].date;
                    }
                }
                break;
            case "121": this.ComboRankPanal.active = false; break;
            case "开始游戏": find("Canvas/Main").active = false; break;
            case "130": director.loadScene("PaoPaoXiGua_Game_Scene"); break
            default:
                break;
        }
    }
    SelectGameModel(event: Event, customEventData: string) {
        // Global.platform.SHOW_BANNER();
        GameData.gameModel = Number(customEventData)
        // SaveData.GameData=[]s
        // SaveData.GameDataScore[GameData.gameModel]=0
        // SaveData.GameDataProp[GameData.gameModel]=[this.Num_qyq[0],this.Num_wan[0],this.Num_yyy[0]]
        // SaveUtils.inst.SaveData()
        find("Canvas/box_rule/modelname").getComponent(Label).string = GameData.gameModelName[GameData.gameModel]
        find("Canvas/ComboRankPanal/frame_blue/name").getComponent(Label).string = "（" + GameData.gameModelName[GameData.gameModel] + "）"
        this.ProgressDetection()
    }
    //    //看广告:道具-万能
    AD_Prop_wan() {
        if (this.CreateNum <= 1) {
            this.meigg("当前没有水果可以合成", false);
        } else {
            if (this.Num_wan[0] < this.Num_wan[1]) {
                let errorVideo = () => {
                    director.resume();
                    console.log("其他情况关闭视频广告")
                }

                let goodVideo = () => {
                    director.resume();
                    console.log("广告成功播放")
                    this.Prop_wan()
                }
                // Global.platform.CLOSE_VIDEO(goodVideo, errorVideo)
            } else {
                this.meigg("万能水果用过一次啦", false);
            }
        }
    }
    Prop_wan() {
        director.resume();
        find("Canvas/Prop/Layout/wan").active = false
        this.Num_wan[0] += 1
        this.CreateNewBall(false, false, 0);
        this.meigg("万能果可以和任意水果合成！", false);
        this.Panel_Prop_wan.active = false;
    }
    //    //看广告:道具-boom
    AD_Prop_boom() {
        if (this.CreateNum <= 1) {
            this.meigg("当前没有水果可以被炸", false);
        } else {
            if (this.Num_boom[0] < this.Num_boom[1]) {
                this.Num_boom[0] += 1
                this.CreateNewBall(false, false, -1);
            } else {
                this.meigg("炸弹用过一次啦", false);
            }
        }
    }
    //    //看广告:道具-敲一敲
    AD_Prop_tap() {
        if (this.CreateNum <= 1) {
            this.meigg("当前没有水果可以消除", false);
        } else {
            let errorVideo = () => {
                director.resume();
                console.log("其他情况关闭视频广告")
            }

            let goodVideo = () => {
                director.resume();
                console.log("广告成功播放")
                this.Prop_tap()
            }
            // Global.platform.CLOSE_VIDEO(goodVideo, errorVideo)
        }
    }
    //    //道具-敲一敲
    Prop_tap() {
        director.resume();
        find("Canvas/Prop/Layout/tap").active = false
        this.meigg("选择一个你想要消除的水果", false);
        this.Num_qyq[0] += 1
        this.Panel_Prop_tap.active = false;
        this.isXiaochu = true;//是否启用了消除道具
    }
    //    //看广告:道具-换一换
    AD_Prop_swap() {
        let errorVideo = () => {
            director.resume();
            console.log("其他情况关闭视频广告")
        }

        let goodVideo = () => {
            director.resume();
            console.log("广告成功播放")
            this.Prop_swap()
        }
        // Global.platform.CLOSE_VIDEO(goodVideo, errorVideo)
    }
    //    //道具-换一换
    Prop_swap() {
        find("Canvas/Prop/Layout/swap").active = false
        this.Num_hyh[0] += 1
        this.Panel_Prop_swap.active = false;
        this.CreateNewBall(false, true);
    }
    //    //看广告:道具-摇一摇
    AD_Prop_shake() {
        let errorVideo = () => {
            director.resume();
            console.log("其他情况关闭视频广告")
        }

        let goodVideo = () => {
            director.resume();
            console.log("广告成功播放")
            this.Prop_shake()
        }
        // Global.platform.CLOSE_VIDEO(goodVideo, errorVideo)
    }
    //    //道具-摇一摇
    Prop_shake() {
        director.resume();
        find("Canvas/Prop/Layout/shake").active = false
        this.Panel_Prop_shake.active = false;
        this.isWUDI = true
        this.scheduleOnce(() => {
            this.isWUDI = false
        }, 10)
        this.Num_yyy[0] += 1
        let i = 1
        let j = 0
        let k = 17
        this.schedule(function () {
            // director.getPhysicsManager().gravity = v2(i * 40000, -3000);
            PhysicsSystem2D.instance.gravity = v2(i * 40000, -3000);


            if (i == 1) { i = -1 } else { i = 1 }
            if (j < 15) { j++ } else { PhysicsSystem2D.instance.gravity = v2(-1, -1280); }
        }, 0.15, k, 0);
    }
    //    //看广告_获取体力
    LookAD_GetPower() {
        let errorVideo = () => {
            director.resume();
            console.log("其他情况关闭视频广告")
        }

        let goodVideo = () => {
            director.resume();
            console.log("广告成功播放")

            this.NOpower.active = false
        }
        // Global.platform.CLOSE_VIDEO(goodVideo, errorVideo)
    }
    //    //关闭获取体力的广告面板
    OpenClose_GetPower(event: Event, customEventData: string) {
        if (customEventData == "0") {
            this.NOpower.active = false
        } else {
            this.NOpower.active = true
            find("/BG/Label2", this.NOpower).active = true
            find("/BG/Label1", this.NOpower).active = false
        }
    }
    //    //tips弹出框
    meigg(str: string, isOnly: boolean, isadd?: boolean) {
        this.meig.active = true;
        if (isadd) { this.meig.getChildByName("Label").getComponent(Label).string += str; } else {
            this.meig.getChildByName("Label").getComponent(Label).string = str;
        }
        this.scheduleOnce(() => {
            if (!isOnly) this.meig.active = false;
        }, 2);
    }
    //    //手指动画
    shou() {
        find("Canvas/Prop/Highlight").active = true
        find("Canvas/Prop/shou").active = true
        let star = find("Canvas/Prop/starAnim").getPosition()
        let end = find("Canvas/Prop/endAnim").getPosition()
        let shou = find("Canvas/Prop/shou")
        tween(shou).repeatForever(
            tween(shou)
                .to(1, { position: v3(end) })
                .to(1, { position: v3(star) })
        ).start();
    }
    //    //关闭高亮提示
    closeHighlight() {
        find("Canvas/Prop/Highlight").active = false
        find("Canvas/Prop/shou").active = false
    }
    IScloseHighlight() {
        this.iscloseHighlight = true
    }
    //    //高亮提示复选框
    ToggleHighlight() {
        SaveData.isPropts = !SaveData.isPropts
        SaveUtils.inst.SaveData()
    }
    //    //分享
    share() {
        // Global.platform.activeShare();
    }
    downTimeNode() {
        this.scheduleOnce(() => {

        })
        this.schedule(() => {
            let time = this.downTime > 0 ? this.downTime-- : 0
            this.downTimeLabel.string = "本期排名 " + Common.timeTransitionString(time, 3) + " 截止"
        }, 1, macro.REPEAT_FOREVER, 0)
    }
    GameClubButtonHide() {
        // Global.platform.GameClubButtonHide();

    }
    loadImgByUrl(imgNode, remoteUrl) {
        assetManager.loadRemote<Texture2D>(remoteUrl, { ext: '.png' }, (err, res) => {
            // var newSpriteFrame = new SpriteFrame(res);
            var newSpriteFrame = new SpriteFrame();
            imgNode.getComponent(Sprite).spriteFrame = newSpriteFrame;
        })

    }
    updateNowRank() {
        if (!this.isUpdateRank) {
            this.isUpdateRank = true
        } else {
            return
        }
        if (this.AllRankInfo != null) {

            for (let index = 0; index < this.AllRankInfo.length; index++) {
                const element = instantiate(this.ItemPrefab);
                element.getChildByName("Rank").getComponent(Label).string = (index + 1).toString()
                let a = ""
                if (this.AllRankInfo[index].gamedata.nickname.length > 7) a = "..."
                element.getChildByName("Name").getComponent(Label).string = this.AllRankInfo[index].gamedata.nickname.substring(0, 6) + a

                element.getChildByName("Score").getComponent(Label).string = this.AllRankInfo[index].gamedata.score0
                this.loadImgByUrl(element.getChildByName("Sprite"), this.AllRankInfo[index].gamedata.avatarUrl)

                if (Global.openid == this.AllRankInfo[index].openid) {
                    this.youRank = (index + 1)
                    // this.youMaxScore = this.AllRankInfo[index].score0
                    // this.younickname = this.AllRankInfo[index].nickname
                }
                if (index <= 0) {
                    element.parent = find("Canvas/Panel_Rank/BG/NowRankBG/view/content/1/Layout")
                } else if (index <= 1) {
                    element.parent = find("Canvas/Panel_Rank/BG/NowRankBG/view/content/2/Layout")
                } else if (index <= 2) {
                    element.parent = find("Canvas/Panel_Rank/BG/NowRankBG/view/content/3/Layout")
                } else if (index <= 9) {
                    element.parent = find("Canvas/Panel_Rank/BG/NowRankBG/view/content/4/Layout")
                } else if (index <= 99) {
                    element.parent = find("Canvas/Panel_Rank/BG/NowRankBG/view/content/5/Layout")
                }
            }
        }
        let a = ""
        if (Global.nickName.length > 10) a = "..."
        find("Canvas/Panel_Rank/BG/NowRankBG/item/Name").getComponent(Label).string = Global.nickName.substring(0, 6) + a
        // find("Canvas/Panel_Rank/BG/NowRankBG/item/Score").getComponent(Label).string = Global.Score_Max_Now + ""
        // find("Canvas/Panel_Star/BG/di1/Score").getComponent(RichText).string =
        //     "<color=#C88442>本期最高分数</c><color=#F14B3E> " + Global.Score_Max_Now + " </color><color=#C88442>分</c>"
        if (this.youRank == -1) {
            find("Canvas/Panel_Rank/BG/NowRankBG/item/Rank").getComponent(Label).string = "100+"
            find("Canvas/Panel_Star/BG/Rank").getComponent(Label).string = "100+"

        } else {
            find("Canvas/Panel_Rank/BG/NowRankBG/item/Rank").getComponent(Label).string = this.youRank + ""
            find("Canvas/Panel_Star/BG/Rank").getComponent(Label).string = this.youRank + ""
        }
        // if (this.AllRankInfoLast != null) {

        //     for (let index = 0; index < 3; index++) {
        //         if (this.AllRankInfoLast[index]) {
        //             let a = ""
        //             if (this.AllRankInfoLast[index].nickname.length > 7) a = "..."
        //             find("Canvas/UI/Panel_Rank/BG/LastRankBG/Rank" + index + "/Name").getComponent(Label).string = this.AllRankInfoLast[index].nickname.substring(0, 6) + a,
        //                 find("Canvas/UI/Panel_Rank/BG/LastRankBG/Rank" + index + "/Score").getComponent(Label).string = this.AllRankInfoLast[index].points
        //         }
        //         this.loadImgByUrl(find("Canvas/UI/Panel_Rank/BG/LastRankBG/Rank" + index + "/Sprite"), this.AllRankInfoLast[index].avatar_url)
        //     }
        // }

        //开始游戏
        // if (Global.Score_Max_Now === 0) {
        //     this.Panel_Rank.active = true
        //     this.LastRankBG.active = true
        //     this.NowRankBG.active=false
        //     find("/more", this.LastRankBG).active = false
        //     find("/share", this.LastRankBG).active = false
        //     find("/close", this.LastRankBG).active = false
        //     find("/close", this.NowRankBG).active = false
        //     find("/star", this.LastRankBG).active = true
        // } else {
        //     this.Panel_Star.active = true
        // }
        find("Canvas/Mask").active = false
        SaveUtils.inst.SaveData()

    }
    UpdateGameData(score: number) {
        let updateTime = Number(new Date().getTime() / 1000);
        let gameData = {
            avatarUrl: Global.avatarUrl,
            nickname: Global.nickName,
            province: "武汉",
            score0: score,
            score1: score * 2,
            weekNumber: 1,
            CloudData: sys.localStorage.getItem('Water_userData')
        }
        // Global.platform.UpdateGameData(gameData)
    }
    DownRankData(rankNum: any) {
        let updateTime = Number(new Date().getTime() / 1000);
        let gameData = {
            rankNum: rankNum
        }
        // Global.platform.DownRankData(gameData)
    }
    DownGameData() {
        // Global.platform.DownGameData()
    }
}